from flask import Blueprint, request, jsonify
from models import db
from models.models import User
from models.users import AdminUser, Role, Resource, Permission
import json

users_blueprint = Blueprint('users_blueprint', __name__)

@users_blueprint.route("/users/")
def users():
    """用户管理接口"""
    try:
        # 创建用户
        ro1 = AdminUser(name='admin1', mobile='12345678901', roleid=1)
        db.session.add(ro1)
        db.session.commit()
        
        return jsonify({
            "code": 200,
            "message": "用户创建成功",
            "data": {
                "username": ro1.username,
                "email": ro1.email,
                "role_id": ro1.role_id
            }
        })
    except Exception as e:
        return jsonify({
            "code": 500,
            "message": f"用户创建失败: {str(e)}"
        }), 500

@users_blueprint.route("/roles/")
def roles():
    """角色管理接口"""
    try:
        # 创建角色
        ro1 = Role(name='主任')
        db.session.add(ro1)
        db.session.commit()
        
        return jsonify({
            "code": 200,
            "message": "角色创建成功",
            "data": {
                "name": ro1.name,
                "id": ro1.id
            }
        })
    except Exception as e:
        return jsonify({
            "code": 500,
            "message": f"角色创建失败: {str(e)}"
        }), 500

@users_blueprint.route("/resources/")
def resources():
    """资源管理接口"""
    try:
        # 创建资源
        resource = Resource(name='销售管理', pid=0, level=1, topid=0)
        db.session.add(resource)
        db.session.commit()
        
        return jsonify({
            "code": 200,
            "message": "资源创建成功",
            "data": {
                "name": resource.name,
                "id": resource.id
            }
        })
    except Exception as e:
        return jsonify({
            "code": 500,
            "message": f"资源创建失败: {str(e)}"
        }), 500

@users_blueprint.route("/role-resources/", methods=['POST'])
def assign_role_resources():
    """为角色分配资源（多对多关系）"""
    try:
        roleid = request.args.get('roleid')
        reslist = request.args.get('reslist')
        
        if not roleid or not reslist:
            return jsonify({
                "code": 400,
                "message": "缺少必要参数"
            }), 400
        
        reslist = json.loads(reslist)
        role = Role.query.filter_by(id=roleid).first()
        
        if not role:
            return jsonify({
                "code": 404,
                "message": "角色不存在"
            }), 404
        
        resource = Resource.query.filter(Resource.id.in_(reslist)).all()
        
        # 删除此角色下所有资源
        role.res = []
        # 添加新的资源
        role.res = resource
        db.session.commit()
        
        return jsonify({
            "code": 200,
            "message": "角色资源分配成功",
            "data": {
                "role_id": role.id,
                "role_name": role.name,
                "resources": [{"id": r.id, "name": r.name} for r in resource]
            }
        })
    except Exception as e:
        return jsonify({
            "code": 500,
            "message": f"角色资源分配失败: {str(e)}"
        }), 500

@users_blueprint.route("/user-menu/")
def get_user_menu():
    """获取用户菜单（树状结构）"""
    try:
        user_id = request.args.get('user_id', 1)
        
        # 查询用户
        user = User.query.get(user_id)
        if not user:
            return jsonify({
                "code": 404,
                "message": "用户不存在"
            }), 404
        
        # 查询用户角色对应的资源
        role = user.role
        if not role:
            return jsonify({
                "code": 404,
                "message": "用户没有分配角色"
            }), 404
        
        # 获取角色对应的资源
        resources = role.res.all()
        
        # 转换为树状结构
        menu_tree = convert_list_to_tree(resources)
        
        return jsonify({
            "code": 200,
            "message": "获取用户菜单成功",
            "data": {
                "user": {
                    "id": user.id,
                    "username": user.username,
                    "role_name": role.name
                },
                "menu": menu_tree
            }
        })
    except Exception as e:
        return jsonify({
            "code": 500,
            "message": f"获取用户菜单失败: {str(e)}"
        }), 500

def convert_list_to_tree(resources):
    """将资源列表转换为树状结构"""
    current_dict = {}
    
    for resource in resources:
        pid = resource.pid
        id = resource.id
        
        if pid not in current_dict:
            current_dict[pid] = {
                'id': pid,
                'name': get_parent_name(pid, resources),
                'children': [{
                    'id': id, 
                    'name': resource.name,
                    'url': resource.url,
                    'icon': resource.icon,
                    'level': resource.level
                }],
            }
        else:
            current_dict[pid]['children'].append({
                'id': id, 
                'name': resource.name,
                'url': resource.url,
                'icon': resource.icon,
                'level': resource.level
            })
    
    return list(current_dict.values())

def get_parent_name(pid, resources):
    """获取父级资源名称"""
    for resource in resources:
        if resource.id == pid:
            return resource.name
    return "根节点"

@users_blueprint.route("/init-data/")
def init_data():
    """初始化测试数据"""
    try:
        # 创建角色
        admin_role = Role(name='超级管理员', description='拥有所有权限')
        manager_role = Role(name='部门经理', description='管理本部门')
        employee_role = Role(name='普通员工', description='基础权限')
        
        db.session.add_all([admin_role, manager_role, employee_role])
        db.session.flush()  # 获取ID
        
        # 创建资源
        sales_mgmt = Resource(name='销售管理', pid=0, level=1, topid=0, url='/sales', icon='el-icon-sell')
        sales_order = Resource(name='销售订单', pid=sales_mgmt.id, level=2, topid=sales_mgmt.id, url='/sales/orders', icon='el-icon-document')
        sales_add = Resource(name='销售订单新增', pid=sales_order.id, level=3, topid=sales_mgmt.id, url='/sales/orders/add', icon='el-icon-plus')
        
        product_mgmt = Resource(name='商品管理', pid=0, level=1, topid=0, url='/products', icon='el-icon-goods')
        product_add = Resource(name='新增商品', pid=product_mgmt.id, level=2, topid=product_mgmt.id, url='/products/add', icon='el-icon-plus')
        
        db.session.add_all([sales_mgmt, sales_order, sales_add, product_mgmt, product_add])
        db.session.flush()
        
        # 创建用户
        admin_user = User(username='admin', email='admin@example.com', role_id=admin_role.id)
        manager_user = User(username='manager', email='manager@example.com', role_id=manager_role.id)
        employee_user = User(username='employee', email='employee@example.com', role_id=employee_role.id)
        
        db.session.add_all([admin_user, manager_user, employee_user])
        
        # 为角色分配资源
        admin_role.res = [sales_mgmt, sales_order, sales_add, product_mgmt, product_add]
        manager_role.res = [sales_mgmt, sales_order, product_mgmt]
        employee_role.res = [sales_order]
        
        db.session.commit()
        
        return jsonify({
            "code": 200,
            "message": "初始化数据成功",
            "data": {
                "roles": 3,
                "resources": 5,
                "users": 3
            }
        })
    except Exception as e:
        db.session.rollback()
        return jsonify({
            "code": 500,
            "message": f"初始化数据失败: {str(e)}"
        }), 500